package com.rfid.manager;

import android.os.Handler;

import com.rfid.a252robot.event.BoxOpenEvent;
import com.rfid.a252robot.event.TaskEvent;
import com.rfid.a252robot.task.BorrowRestoreTask;
import com.rfid.a252robot.task.CheckFailTask;
import com.rfid.a252robot.task.ITask;
import com.rfid.common.log.LogUtils;
import com.rfid.util.Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class  TaskManager {

    static TaskManager taskManager = new TaskManager();
    public ExecutorService mExecutor = Executors.newCachedThreadPool();
    List<ITask> mTasks = new ArrayList<>();

    static List<Integer> mNeedCheckBoxes = new ArrayList<>();

    Handler handler = new Handler();
    Timer timer;

    private TaskManager() {
        EventBus.getDefault().register(this);
    }

    public static TaskManager instance() {
        return taskManager;
    }

    public int getEmptyBox() {
        List<Integer> emptyBoxes = Util.getEmptyBoxes();
//        List<Integer> lboxes = lowPriorityBoxes();
//        LogUtils.v(" emptyBoxes = " + emptyBoxes.size());
//        for (Integer b : lboxes) {
//            boolean r= emptyBoxes.remove(b);
//            LogUtils.v("remove lowPriorityBoxes b = " + b + ":" + Util.getBoxShow(b) + "," + r);
//        }
        LogUtils.v(emptyBoxes.size());
//        if (emptyBoxes.size() == 0) {
//            LogUtils.v("reload emptyBoxes");
//            emptyBoxes = Util.getEmptyBoxes();
//        }
        for (ITask task:mTasks) {
            emptyBoxes.remove(Integer.valueOf(task.getBoxNum()));
        }
        int s = -1;
        LogUtils.v("emptyBoxes = " + emptyBoxes);
        if (emptyBoxes.size() > 0) {
            s = emptyBoxes.get((int) Math.round(Math.random() * (emptyBoxes.size() - 1)));
        }
        return s;
    }

    private List<Integer> lowPriorityBoxes() {
        List<Integer> boxes = new ArrayList<>();
        boxes.add(Integer.valueOf(1));
        boxes.add(Integer.valueOf(9));
        boxes.add(Integer.valueOf(15));
        boxes.add(Integer.valueOf(23));

        boxes.add(Integer.valueOf(29));
        boxes.add(Integer.valueOf(37));
        boxes.add(Integer.valueOf(43));
        boxes.add(Integer.valueOf(51));
        return boxes;
    }

    public String submitTask(ITask task,boolean force) {
        if (mTasks.size() > 0 && !force) {
            if (task instanceof BorrowRestoreTask) {
                if (task.isBorrow()) {
                    if (mTasks.size() > 0) {
                        int cnt = 0;
                        for (ITask task1 : mTasks) {
                            if (!task1.isBoxClose()) {
                                if (task.getBoxNum() != task1.getBoxNum()) {
                                    return Util.getBoxShow(task1.getBoxNum()) + " 号柜门未关，请先关闭柜门后再借阅";
                                }
                            } else {
                                cnt++;
                            }
                        }
                        if (cnt == mTasks.size()) {
                            return "";
                        }
                    }
                } else {
                    for (ITask task1 : mTasks) {
                        if (!task1.isBoxClose()) {
                            if (task.getBoxNum() != task1.getBoxNum()) {
                                return Util.getBoxShow(task1.getBoxNum()) + " 号柜门未关，请先关闭柜门后再归还";
                            }
                        }
                    }
                }
                if (!task.isBorrow()) {
                    int box = -1;
                    for (ITask task1 : mTasks) {
                        if (!task1.isBoxClose()) {
                            LogUtils.v("submitTask restore door not close " + task1.getBoxNum());
                            box = task1.getBoxNum();
                        }
                    }
                    if (box != -1) {
                        LogUtils.v("submitTask restore return opened door " + box);
                        EventBus.getDefault().post(new BoxOpenEvent(box, true));
                        return "";
                    }
                }
            }
        }
//        if (mTasks.contains(task)) {
//            LogUtils.v("task is Doing!! > box = " + task.getBoxNum() + ", borrow = " + task.isBorrow());
//        }

/*        for (ITask task1 : mTasks) {
            if (task1.getBoxNum() == task.getBoxNum()) {
                task.setBoxNum(getEmptyBox());
                break;
            }
        }*/
        mTasks.add(task);
        mExecutor.execute(task);
        return String.format("正在开启%s号门",Util.getBoxShow(task.getBoxNum()) + "");
    }

    public void submit(Runnable runnable) {
        mExecutor.execute(runnable);
    }


    public void startCheckTask() {
        if (timer != null) {
            timer.cancel();
            timer = new Timer();
        } else {
            timer = new Timer();
        }
        long delay = 5000;
        long period = 60000;
        timer.scheduleAtFixedRate(new CheckFailTask(), delay, period);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTaskEndEvent(TaskEvent event) {
        LogUtils.v("onTaskEndEvent = " + event);
        mTasks.remove(event.getTask());
    }

}
